

using AgNuget4Vue;
using OfficeOpenXml;
using StandardManager.DB;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Data.SQLite;
using System.Text;

namespace Jixiao
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var selYear = this.comboBoxYearMonth.SelectedItem.ToString();

            var dt = DateTime.Now;
            var changeLastMonth = selYear;
            if (dt.Day < 10)
            {
                var dr = MessageBox.Show("检测到本月刚开始，是否按照上月的内容打印输出?", "时间调整", MessageBoxButtons.YesNo);
                if (dr == DialogResult.Yes)
                {
                    var dt2 = dt.AddMonths(-1);
                    changeLastMonth = dt2.Year + "年" + (dt2.Month) + "月";
                }
            }

            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "*.xls|*.xls";
            dlg.FileName = m_lastUserName + "员工绩效考核表" + changeLastMonth;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                ExcelOut excelOut = new ExcelOut()
                {
                    m_lastUserName = m_lastUserName,
                    m_allItems = m_allItems
                };
                excelOut.Export(selYear, dlg.FileName, changeLastMonth);
            }
        }

        private void 新增任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormNewTask formNewTask = new FormNewTask()
            {
                StartPosition = FormStartPosition.CenterScreen,
                UserName = this.comboBox1.Text,
                HasRichangWork = HasRiChangWork("日常工作"),
                HasXieTongWork = HasRiChangWork("协同工作"),
            };
            formNewTask.ShowDialog();

            this.UpdateListView();
        }
        private bool HasRiChangWork(string workName)
        {
            var currentItems = listView1.Items;
            var a = "";
            for (var i = 0; i < currentItems.Count; i++)
            {
                TaskItem item = currentItems[i].Tag as TaskItem;
                if (item.ProjectName.Trim() == workName)
                {
                    return true;
                }
            }
            return false;
        }


        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form1_Load(null, null);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            UpdateListView();

            this.comboBoxYearMonth.Items.Clear();
            this.comboBoxYearMonth.Items.Add("-All-");
            this.comboBoxYearMonth.Items.Add("2025年1月");
            this.comboBoxYearMonth.Items.Add("2025年2月");
            this.comboBoxYearMonth.Items.Add("2025年3月");
            this.comboBoxYearMonth.Items.Add("2025年4月");
            this.comboBoxYearMonth.Items.Add("2025年5月");
            this.comboBoxYearMonth.Items.Add("2025年6月");
            this.comboBoxYearMonth.Items.Add("2025年7月");
            this.comboBoxYearMonth.Items.Add("2025年8月");
            this.comboBoxYearMonth.Items.Add("2025年9月");
            this.comboBoxYearMonth.Items.Add("2025年10月");
            this.comboBoxYearMonth.Items.Add("2025年11月");
            this.comboBoxYearMonth.Items.Add("2025年12月");
            this.comboBoxYearMonth.Items.Add("2026年1月");
            this.comboBoxYearMonth.Items.Add("2026年2月");
            this.comboBoxYearMonth.Items.Add("2026年3月");

            this.comboBoxYearMonth.SelectedIndex = this.comboBoxYearMonth.Items.Count - 1;
        }

        public static ConnectionDatabase_S2 Connection
        {
            get
            {
                ConnectionDatabase_S2 connectionDatabase_S2 = ConnectionDatabase_S2.BuildSqliteConnection(Setting.DBName);
                return connectionDatabase_S2;
            }
        }

        private List<ListViewItem> m_allItems = new List<ListViewItem>();
        private string m_lastUserName = string.Empty;
        private string m_lastProjectName = string.Empty;
        private string m_yearMonth = string.Empty;
        private void UpdateListView()
        {
            var connection = Connection;
            var dt = connection.SelectData("select * from  TaskList");

            listView1.Items.Clear();

            List<string> userNames = new List<string>();
            List<string> projectNames = new List<string>();
            m_allItems.Clear();

            for (var i = 0; i < dt.Rows.Count; i++)
            {
                TaskItem item = TaskItem.FromRow(dt.Rows[i]);

                userNames.Add(item.MyName);
                projectNames.Add(item.ProjectName);

                var lvi = item.ToListViewItem();

                this.listView1.Items.Add(lvi);

                m_allItems.Add(lvi);
            }
            m_enableFilter = false;
            this.comboBox1.Items.Clear();
            this.comboBox1.Items.Add("-All-");
            this.comboBox1.Items.AddRange(userNames.Distinct().ToArray());

            this.comboBox2.Items.Clear();
            this.comboBox2.Items.Add("-All-");
            this.comboBox2.Items.AddRange(projectNames.Distinct().ToArray());




            if (string.IsNullOrEmpty(m_lastUserName) == false)
            {
                this.comboBox1.SelectedItem = m_lastUserName;
            }
            if (string.IsNullOrEmpty(m_lastProjectName) == false)
            {
                this.comboBox2.SelectedItem = m_lastProjectName;
            }
            if (string.IsNullOrEmpty(m_yearMonth) == false)
            {
                this.comboBoxYearMonth.SelectedItem = m_yearMonth;
            }

            m_enableFilter = true;
            OnFilter();
        }

        private void 标记完成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count == 0) return;
            var lvi = this.listView1.SelectedItems[0];

            TaskItem item = lvi.Tag as TaskItem;
            item.IsFinish = true;
            item.EndTime = DateTime.Now;

            var sql = item.BuildUpdateSql();

            var connection = Connection;
            connection.ExecuteSQL(sql);

            UpdateListView();
        }

        #region 过滤
        private bool m_enableFilter = true;
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            OnFilter();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            OnFilter();
        }
        private void OnFilter()
        {
            if (m_enableFilter == false) return;
            listView1.Items.Clear();
            var str = comboBox1.Text;
            if (str == "-All-") { str = ""; }
            var projectName = this.comboBox2.Text;
            if (projectName == "-All-") { projectName = ""; }
            var yearMonth = this.comboBoxYearMonth.Text;
            if (yearMonth == "-All-") { yearMonth = ""; }

            m_lastUserName = str;
            m_lastProjectName = projectName;
            m_yearMonth = yearMonth;

            for (var i = 0; i < m_allItems.Count; i++)
            {
                TaskItem item = m_allItems[i].Tag as TaskItem;
                var t1 = (string.IsNullOrEmpty(str) || item.MyName == str);
                if (!t1) continue;
                var dt = item.StartTime;
                var yearMonthThis = (dt.Year + "年" + (dt.Month) + "月");
                var dt2 = item.EndTime;
                var yearMonthThis2 = (dt2.Year + "年" + (dt2.Month) + "月");

                var t3 = item.ProjectName == "日常工作" || item.ProjectName == "协同工作";

                if (t3 || (string.IsNullOrEmpty(projectName) || item.ProjectName == projectName)
                    && (string.IsNullOrEmpty(m_yearMonth) || yearMonthThis == m_yearMonth || yearMonthThis2 == m_yearMonth))
                {
                    listView1.Items.Add(m_allItems[i]);
                }
            }
        }

        #endregion

        #region 去重
        private void 去重ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var currentItems = listView1.Items;
            var a = "";
            for (var i = 0; i < currentItems.Count; i++)
            {
                TaskItem item = currentItems[i].Tag as TaskItem;
                for (var j = i + 1; j < currentItems.Count; j++)
                {
                    TaskItem itemB = currentItems[j].Tag as TaskItem;
                    if (item.EqualsSame(itemB))
                    {
                        ConnectionDatabase_S2 connectionDatabase_S2 = ConnectionDatabase_S2.BuildSqliteConnection(Setting.DBName);
                        string sql = $"delete from TaskList where taskName='" + itemB.TaskName + $"' and rowNumber='{itemB.RowNumber}'";
                        connectionDatabase_S2.ExecuteSQL(sql);

                        itemB.UUID = Guid.NewGuid().ToString();
                        var sql2 = itemB.CreateInsertSql();
                        connectionDatabase_S2.ExecuteSQL(sql2);
                        a = "删除重复的" + itemB.TaskName;
                        break;
                    }
                }
                if (string.IsNullOrEmpty(a) == false)
                {
                    break;
                }
            }
            if (string.IsNullOrEmpty(a))
            {
                MessageBox.Show("没有重复的.");
            }
            else
            {
                MessageBox.Show(a);

                UpdateListView();
            }
        }
        #endregion

        #region 重新编辑
        private void 重新编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count == 0) return;
            var lvi = this.listView1.SelectedItems[0];

            TaskItem item = lvi.Tag as TaskItem;
            FormNewTask formNewTask = new FormNewTask()
            {
                StartPosition = FormStartPosition.CenterScreen,
                EditItem = item
            };
            formNewTask.ShowDialog();

            this.UpdateListView();
        }
        private void 设为上月任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count == 0) return;
            var lvi = this.listView1.SelectedItems[0];

            TaskItem item = lvi.Tag as TaskItem;
            item.StartTime= item.StartTime.AddMonths(-1);
            item.EndTime= item.EndTime.AddMonths(-1);

            ConnectionDatabase_S2 connectionDatabase_S2 = ConnectionDatabase_S2.BuildSqliteConnection(Setting.DBName);
            var sql=item.BuildUpdateSql();
            connectionDatabase_S2.ExecuteSQL(sql);

            this.UpdateListView();
        }
        #endregion

        private void 打开本地数据库ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog()
            {
                Filter = "*.db|*.db"
            };
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Setting.DBName = dlg.FileName;
                UpdateListView();
            }
        }

        #region 设置项目权重
        private void 项目权重ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<string> projectNames = new List<string>();
            var items = ProjectListInfo.FilterItemsByUserName(m_lastUserName, m_allItems, projectNames, m_yearMonth);
            if (items == null) return;

            FormExcelOutConfig form = new FormExcelOutConfig()
            {
                StartPosition = FormStartPosition.CenterScreen,
                UserName = m_lastUserName,
                ProjectNames = projectNames,
                Connection = Connection
            };
            form.ShowDialog();
        }
        private void 历来绩效ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormHistory form = new FormHistory()
            {
                StartPosition = FormStartPosition.CenterScreen,
            };
            form.ShowDialog();
        }
        private void 月度打分ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormPin form = new FormPin()
            {
                StartPosition = FormStartPosition.CenterScreen,
                m_allItems = m_allItems
            };
            form.ShowDialog();
        }
        #endregion


        
    }
}
